Skip to main content

Navigation

Navigation in @tata1mg/router is based on react-router-v6, and client side navigation can be achieved through components like <Navigate> or <Link> or through hooks like useNavigate.

Using useNavigate Hook

Example of programmatic navigation using the useNavigate hook:

import { useNavigate } from "@tata1mg/router";

function useLogoutTimer() {
const userIsInactive = useFakeInactiveUser();
const navigate = useNavigate();

useEffect(() => {
if (userIsInactive) {
fake.logout();
navigate("/session-timed-out");
}
}, [userIsInactive]);
}

For declarative navigation, use the Link component:

import { Link } from "@tata1mg/router";

function NavigationMenu() {
return (
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
<Link to="/products">Products</Link>
<Link to="/user/123">User Profile</Link>
</nav>
);
}

Client-Side Navigation

Navigation inside clientFetcher function can be achieved through the navigate property which is available as an argument in clientFetcher.

Home.clientFetcher = async ({navigate}) => {
// Check if user is authenticated
const isAuthenticated = await checkAuth();

if (!isAuthenticated) {
navigate("/login");
return;
}

// Continue with data fetching
const data = await fetchUserData();
return data;
}

Server-Side Navigation

Navigation inside serverFetcher function can also be achieved through the navigate property which is available as an argument in serverFetcher. navigate available inside server fetcher is a wrapper around response.send() so it would result it server side navigation.

Home.serverFetcher = async ({navigate}) => {
// Check authentication on server
const isAuthenticated = await checkServerAuth();

if (!isAuthenticated) {
navigate("/login");
// Will be navigated to /login on the server
return;
}

// Continue with server-side data fetching
const data = await fetchServerData();
return data;
}

You can navigate to routes with dynamic parameters:

import { useNavigate } from "@tata1mg/router";

function UserList() {
const navigate = useNavigate();

const handleUserClick = (userId) => {
navigate(`/user/${userId}`);
};

return (
<div>
{users.map(user => (
<button
key={user.id}
onClick={() => handleUserClick(user.id)}
>
View {user.name}
</button>
))}
</div>
);
}

Pass state during navigation:

import { useNavigate } from "@tata1mg/router";

function ProductCard({ product }) {
const navigate = useNavigate();

const handleViewProduct = () => {
navigate("/product/detail", {
state: {
productId: product.id,
fromPage: "product-list"
}
});
};

return (
<div onClick={handleViewProduct}>
<h3>{product.name}</h3>
<p>{product.description}</p>
</div>
);
}